package com.hansen.library.ui.widget.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.hansen.library.Constants;
import com.hansen.library.R;
import com.hansen.library.listener.OnSureCancelListener;
import com.hansen.library.utils.LogUtils;

import java.lang.reflect.Field;

/**
 * Created by han on 2019/1/4 0004.
 */

public class Material2Dialog extends DialogFragment {
    private Dialog mDialog;

    //标题
    private TextView tv_md2_title;
    //内容
    private TextView tv_md2_content;

    //确认
    private Button btn_md2_dialog_sure;
    //取消
    private Button btn_md2_dialog_cancel;

    private OnSureCancelListener onSureListener;

    private int mType;

    private String mParams;

    public static Material2Dialog newInstance(String content) {
        return newInstance(0, null, content, null, true);
    }

    public static Material2Dialog newInstance(String content, String params) {
        return newInstance(0, null, content, params, true);
    }

    public static Material2Dialog newInstance(String content, boolean showCancel) {
        return newInstance(0, null, content, null, showCancel);
    }

    public static Material2Dialog newInstance(int type, String content) {
        return newInstance(type, null, content, null, true);
    }

    public static Material2Dialog newInstance(int type, String content, String params) {
        return newInstance(type, null, content, params, true);
    }

    public static Material2Dialog newInstance(int type, String content, String params, boolean showCancel) {
        return newInstance(type, null, content, params, showCancel);
    }

    public static Material2Dialog newInstance(String content, String params, boolean showCancel) {
        return newInstance(0, null, content, params, showCancel);
    }

    public static Material2Dialog newInstance(String title,  String content, String params, boolean showCancel) {
        return newInstance(0, title, content, params, showCancel);
    }

    public static Material2Dialog newInstance(int type, String title, String content, String params, boolean showCancel) {
        //把所有需要传递的数据都放在Bundle中
        Bundle bundle = new Bundle();

        bundle.putInt(Constants.KeyType, type);
        bundle.putString(Constants.KeyTitle, title);
        bundle.putString(Constants.KeyId, params);
        bundle.putString(Constants.KeyTextContents, content);
        bundle.putBoolean(Constants.KeyShowCancel, showCancel);

        Material2Dialog mMaterialSingleDialog = new Material2Dialog();

        //通过setArguments把Bundle传递过去
        mMaterialSingleDialog.setArguments(bundle);

        return mMaterialSingleDialog;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            if(getParentFragment() != null) {
                onSureListener = (OnSureCancelListener) getParentFragment();
            } else {
                onSureListener = (OnSureCancelListener) context;
            }
        } catch (ClassCastException e) {
            LogUtils.e(context.toString() + " must implement OnSureCancelListener");
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // 定义Dialog布局和参数
        mDialog = new Dialog(getActivity(), R.style.MaterialDialogStyle);

        // 获取Dialog布局
        View view = LayoutInflater.from(getActivity()).inflate(
                R.layout.dialog_material2, null);

        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
        mDialog.setContentView(view);
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setCancelable(false);
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    return true;
                }
                return false;
            }
        });

        tv_md2_title = view.findViewById(R.id.tv_md2_title);
        tv_md2_content = view.findViewById(R.id.tv_md2_content);

        btn_md2_dialog_sure = view.findViewById(R.id.btn_md2_dialog_sure);
        btn_md2_dialog_cancel = view.findViewById(R.id.btn_md2_dialog_cancel);

        Window dialogWindow = mDialog.getWindow();
        dialogWindow.setGravity(Gravity.CENTER);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();

        lp.gravity = Gravity.CENTER; // 居中
        lp.dimAmount = 0.5f;
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平

        dialogWindow.setAttributes(lp);
        dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        btn_md2_dialog_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                if (onSureListener != null) {
                    onSureListener.onSure(mType, mParams);
                }
            }
        });

        btn_md2_dialog_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                if (onSureListener != null) {
                    onSureListener.onCancel(mType);
                }
            }
        });

        Bundle bundle = this.getArguments();//得到从Activity传来的数据

        if (bundle != null) {
            mType = bundle.getInt(Constants.KeyType, 0);

            boolean showTitle = bundle.getBoolean(Constants.KeyShowTitle, true);
            boolean showCancel = bundle.getBoolean(Constants.KeyShowCancel, true);

            String title = bundle.getString(Constants.KeyTitle);
            String content = bundle.getString(Constants.KeyTextContents);
            mParams = bundle.getString(Constants.KeyId);

            tv_md2_title.setVisibility(showTitle && title != null ? View.VISIBLE : View.GONE);
            if(tv_md2_title.getVisibility() == View.VISIBLE) tv_md2_title.setText(showTitle ? (title != null ? title : getString(R.string.text_tips)) : "");
            tv_md2_content.setText(content != null ? content : getString(R.string.text_tips));

            btn_md2_dialog_cancel.setVisibility(showCancel ? View.VISIBLE : View.GONE);
        }

        return mDialog;
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        Fragment mFragment = manager.findFragmentByTag(tag);
        //防止java.lang.IllegalStateException: Fragment already added
        if (mFragment == null || !mFragment.isAdded()) {
            //super.show(manager, tag);
            try {
                Field mDismissed = this.getClass().getSuperclass().getDeclaredField("mDismissed");
                Field mShownByMe = this.getClass().getSuperclass().getDeclaredField("mShownByMe");
                mDismissed.setAccessible(true);
                mShownByMe.setAccessible(true);
                mDismissed.setBoolean(this, false);
                mShownByMe.setBoolean(this, true);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            FragmentTransaction ft = manager.beginTransaction();
            ft.add(this, tag);
            ft.commitAllowingStateLoss();
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
    }

    @Override
    public void dismiss() {
        //super.dismiss();
        dismissAllowingStateLoss();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        onSureListener = null;
    }
}
